package pl.edu.agh.pros.internal.proxy.topic;

import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.ros.message.MessageListener;
import org.ros.namespace.GraphName;
import org.ros.node.ConnectedNode;
import org.ros.node.topic.Subscriber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pl.edu.agh.pros.conf.ProxyConfiguration;
import pl.edu.agh.pros.internal.proxy.AbstractProxyNode;
import pl.edu.agh.pros.internal.proxy.ProxyDispatcher;
import pl.edu.agh.pros.util.RosMessageUtils;

public class ProxyTopicSender extends AbstractProxyNode {

	private static final Logger logger = LoggerFactory.getLogger(ProxyTopicSender.class);
	private Subscriber<org.ros.internal.message.Message> subscriber;
	private MultiUserChat muc;

	public ProxyTopicSender(ProxyDispatcher proxyDispatcher, ProxyConfiguration proxyNodeConfiguration) {
		super(proxyDispatcher, proxyNodeConfiguration);
	}

	@Override
	public GraphName getDefaultNodeName() {
		return new GraphName("pros_core/proxyTopicSender"); //$NON-NLS-1$
	}

	@Override
	public void onStart(final ConnectedNode node) {
		this.node = node;
		subscriber = node.newSubscriber(proxyNodeConfiguration.getName(), proxyNodeConfiguration.getType());
		muc = proxyDispatcher.joinMultiUserChat(null, proxyNodeConfiguration.getName());
		if (muc != null) {
			subscriber.addMessageListener(new MessageListener<org.ros.internal.message.Message>() {
				@Override
				public void onNewMessage(org.ros.internal.message.Message message) {
					try {
						Message xmppMessage = RosMessageUtils.serializeMessage(message, node,
								proxyNodeConfiguration.getType(), muc);
						muc.sendMessage(xmppMessage);
					} catch (Exception e) {
						logger.debug("Can not send message.", e); //$NON-NLS-1$
					}
				}
			});
		} else {
			node.shutdown();
		}
	}

	@Override
	public void dispose() {
		if (muc != null && proxyDispatcher.isConnected() && muc.isJoined()) {
			try {
				muc.leave();
			} catch (Exception e) {
				// ignore
			}
		}
	}

}
